package com.jsbb.core.exception;

import com.jsbb.core.Message;
import com.jsbb.util.JsonUtils;
import com.jsbb.util.LoggerUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理
 *
 * @author jsbb
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Message exceptionHandler(HttpServletRequest request, Exception exception) {
        LoggerUtils.error("系统错误={},", request.getRequestURL(), exception);
        return Message.error("系统错误");
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Message methodNotSupportHandler(HttpServletRequest request, HttpRequestMethodNotSupportedException e) {
        LoggerUtils.error("不支持的请求方法={},", request.getRequestURL(), e);
        return Message.error("不支持的请求方法");
    }

    @ExceptionHandler(value = {ServiceException.class})
    public Message serviceExceptionHandler(HttpServletRequest request, ServiceException serviceException) {
        Message message = new Message(serviceException.getCode(), serviceException.getMsg(), null);
        LoggerUtils.error("业务异常={},接口响应={}", request.getRequestURL(), JsonUtils.toJsonString(message));
        return message;
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Message methodArgumentNotValidHandler(HttpServletRequest request, MethodArgumentNotValidException exception) {
        StringBuilder sb = new StringBuilder();
        for (FieldError error : exception.getBindingResult().getFieldErrors()) {
            sb.append(error.getField()).append(error.getDefaultMessage()).append(";");
        }
        LoggerUtils.error("参数验证失败={},{}", request.getRequestURL(), sb);
        return Message.error("参数验证失败");
    }
}
